package com.yc.mvplib.Retrofit.net;

import android.text.TextUtils;

import com.yc.mvplib.Retrofit.HttpConfig;

import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * Created by lenovo on 2017/12/4.
 * 网络基类
 */

public class RetrofitFactory {
    private static RetrofitFactory mRetrofitFactory;
    private Retrofit  mRetrofit;
    private String baseUrl= HttpConfig.BASE_URL;
    private RetrofitFactory(){
        getmRetrofit();
    }

    public static RetrofitFactory getInstence(){
        if (mRetrofitFactory==null){
            synchronized (RetrofitFactory.class) {
                if (mRetrofitFactory == null)
                    mRetrofitFactory = new RetrofitFactory();
            }
        }
        return mRetrofitFactory;
    }

    private void getmRetrofit() {
          mRetrofit=new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())//添加gson转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加rxjava转换器
                .client(getClient())
                .build();

    }
    public <T> T getRetrofit(Class<T> service) {
        return getRetrofit("",service);
    }
    public <T> T getRetrofit(String url, Class<T> service) {
       if (!TextUtils.isEmpty(url)){
            baseUrl=url;
           mRetrofit=null;
       }
        if (null==mRetrofit){
            getmRetrofit();
        }
        return mRetrofit.create(service);
    }
    /**
     * okhttp客户端做底层
     * @return
     */
    private OkHttpClient getClient() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.retryOnConnectionFailure(true)
                .readTimeout(HttpConfig.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(HttpConfig.DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(HttpConfig.DEFAULT_TIMEOUT, TimeUnit.SECONDS) //设置超时
                .hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                //设置网络连接失败时自动重试
                .retryOnConnectionFailure(true)
                .addNetworkInterceptor(InterceptorUtil.LogInterceptor());

        //使用自定义SSLSocketFactory
        if (getSSLSocketFactory()!=null){
                httpClientBuilder.sslSocketFactory(getSSLSocketFactory());
                }
        return httpClientBuilder.build();
    }

    private SSLSocketFactory getSSLSocketFactory() {
        //创建一个不验证证书链的证书信任管理器。
        final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[0];
            }
        }};

        // Install the all-trusting trust manager
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts,
                    new java.security.SecureRandom());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Create an ssl socket factory with our all-trusting manager
        if (null!=sslContext){

            return sslContext
                    .getSocketFactory();
        }else {
            return null;
        }
    }


}
